/**
 * @ author: 汪孟苹
 */
define(["jquery","template","bbcare","fu/app/comm/comm"],function($,template,$bb,$comm){
	var servers = {};
	/**
	 * 获取url地址,当前用户
	 */
	var URL = $bb.baseUrl("followup");
    /**
     * 组合题型时，按index分配validate
     */
    var validateGroupData = function(validate,i){
        if(typeof validate == "string"){
            validate = JSON.parse(validate);
        }
        var arr = [];
        for (var j = 0; j < validate.length; j++) {
            if(!validate[j].index) validate[j].index = 0;
            if(validate[j].index == i){
                arr.push(validate[j]);
            }
        }
        return JSON.stringify(arr);
    }
    /**
     * question_gestationSimple题型 数据处理
     */
    var gestationSimpleData = function(params){
        var arr = [];
        var length = parseInt(params.length / params.id.length);
        var children_default = {
            "label": ["出生日期","预产期"],
            "subType": ["question_date","question_date"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.labelLength = params.labelLength;
            obj.label = params.label[i];
            obj.type = params.subType[i];
            obj.length = length;
            if(params.validate && params.validate.length > 0 ){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention.length > 0 ){
                obj.attention = validateGroupData(params.attention,i);
            }
            arr.push(obj);
        }
        return arr;
    }
    /**
     * question_gestationComplex题型 数据处理
     */
    var gestationComplexData = function(params){
        var arr = [];
        var length = parseInt(params.length / params.id.length);
        var children_default = {
            "label": ["出生日期","预产期","孕周"],
            "subType": ["question_date","question_date","question_multiSelectNumber"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.labelLength = params.labelLength;
            obj.label = params.label[i];
            obj.type = params.subType[i];
            obj.length = length;
            if(params.validate && params.validate.length > 0 ){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention.length > 0 ){
                obj.attention = validateGroupData(params.attention,i);
            }
            arr.push(obj);
        }
        arr[2].list = [];
        var arrWeek = [], arrDay = []; 
        for (var i = params.minGestation; i <= 45; i++) {
            arrWeek.push(i);
        }
        for (var i = 0; i <= 6; i++) {
            arrDay.push(i);
        }
        var list = {
            sublist: [arrWeek,arrDay],
            subunit: ["周","天"],
            val: [40,0],
            textWidth: ["2em","2em"],
            width: ["50%","50%"]
        };
        for (var i = 0; i < list.sublist.length; i++) {
            var obj = {};
            obj.sublist = list.sublist[i];
            obj.subunit = list.subunit[i];
            obj.val = list.val[i];
            obj.textWidth = list.textWidth[i];
            obj.width = list.width[i];
            arr[2].list.push(obj);
        }
        return arr;
    }
    /**
     * question_correctAge题型 数据处理
     */
    var correctAgeData = function(params){
        var arr = [];
        var length = parseInt(params.length / params.id.length);
        var children_default = {
            "label": ["出生日期","预产期","纠正胎龄（天）"],
            "subType": ["question_date","question_date","question_text"],
            "placeHolder": ["","","请输入纠正胎龄"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.labelLength = params.labelLength;
            obj.label = params.label[i];
            obj.type = params.subType[i];
            obj.placeHolder = params.placeHolder[i];
            obj.length = length;
            if(params.validate && params.validate.length > 0 ){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention.length > 0 ){
                obj.attention = validateGroupData(params.attention,i);
            }
            arr.push(obj);
        }
        return arr;
    }
    /**
     * question_overallBirth题型 数据处理
     */
    var overallBirthData = function(params){
        var arr = [];
        //var length = parseInt(params.length / params.id.length);
        var children_default = {
            "label": ["出生日期","预产期","孕周","纠正胎龄（天）"],
            "subType": ["question_date","question_date","question_multiSelectNumber","question_text"],
            "placeHolder": ["","","请输入纠正胎龄"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.labelLength = params.labelLength;
            obj.label = params.label[i];
            obj.type = params.subType[i];
            obj.placeHolder = params.placeHolder[i];
            obj.length = params.length;
            if(params.validate && params.validate.length > 0 ){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention.length > 0 ){
                obj.attention = validateGroupData(params.attention,i);
            }
            arr.push(obj);
        }
        arr[2].list = [];
        var arrWeek = [], arrDay = []; 
        for (var i = params.minGestation; i <= 45; i++) {
            arrWeek.push(i);
        }
        for (var i = 0; i <= 6; i++) {
            arrDay.push(i);
        }
        var list = {
            sublist: [arrWeek,arrDay],
            subunit: ["周","天"],
            val: [40,0],
            textWidth: ["2em","2em"],
            width: ["50%","50%"]
        };
        for (var i = 0; i < list.sublist.length; i++) {
            var obj = {};
            obj.sublist = list.sublist[i];
            obj.subunit = list.subunit[i];
            obj.val = list.val[i];
            obj.textWidth = list.textWidth[i];
            obj.width = list.width[i];
            arr[2].list.push(obj);
        }
        return arr;
    }
    /**
     * question_growthComplexData题型 数据处理
     */
    var growthComplexData = function(params){
        var arr = [];
        var length = parseInt(params.length / params.id.length);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.length = length;
            obj.labelLength = params.labelLength;
            obj.label = params.label[i];
            obj.placeHolder = params.placeHolder[i];
            if(params.validate && params.validate != ""){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention != "" ){
                obj.attention = validateGroupData(params.attention,i);
            }
            arr.push(obj);
        }
        arr[0].calcType = params.calcType;
        arr[0].unit = params.unit;
        return arr;
    }
    /**
     * question_radioInput题型 数据处理
     */
    var radioInputData = function(params){
        var arr = [];
        var children_default = {
            "subType": ["question_radio","question_text"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.label = params.label[i];
            obj.length = params.length[i];
            obj.labelLength = params.labelLength;
            obj.type = params.subType[i];
            if(params.validate && params.validate != ""){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention != "" ){
                obj.attention = validateGroupData(params.attention,i);
            }
            arr.push(obj);
        }
        arr[0].list = params.list;
        arr[0].val = params.val;
        arr[0].relevantText = params.relevantText;
        arr[1].placeHolder = params.placeHolder;
        return arr;
    }
    /**
     * question_checkboxInput题型 数据处理
     */
    var checkboxInputData = function(params){
        var arr = [];
        var children_default = {
            "subType": ["question_checkbox","question_text"],
        };
        params = $.extend(children_default,params);
        for (var i = 0; i < params.id.length; i++) {
            var obj = {};
            obj.id = params.id[i];
            obj.label = params.label[i];
            obj.length = params.length[i];
            obj.labelLength = params.labelLength;
            obj.type = params.subType[i];
            if(params.validate && params.validate != ""){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention != "" ){
                obj.attention = validateGroupData(params.attention,i);
            }
            arr.push(obj);
        }
        arr[0].list = params.list;
        arr[0].val = params.val;
        arr[0].relevantText = params.relevantText;
        arr[1].placeHolder = params.placeHolder;
        return arr;
    }
    /**
     * question_address题型 数据处理
     */
    var addressData = function(params){
        params.list = [];
        var list = {
            subunit: ["省","市","区/县"],
            val: ["省","市","区/县"]
        };
        for (var i = 0; i < list.subunit.length; i++) {
            var obj = {};
            obj.subunit = list.subunit[i];
            obj.val = list.val[i];
            if(params.validate && params.validate != ""){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention != "" ){
                obj.attention = validateGroupData(params.attention,i);
            }
            params.list.push(obj);
        }
        return params;
    }
    /**
     * question_imagesMultiText题型 数据处理
     */
    var imagesMultiTextData = function(params){
        // ??? images暂时模拟用报文配置
        /*params.images = [];
        var images = {
            src: ["http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/department/educationLogo/1498202450726.jpg","http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/department/educationLogo/1498202436459.jpg","http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/department/educationLogo/1498202425855.jpg"]
        };
        for (var i = 0; i < images.src.length; i++) {
            var obj = {};
            obj.src = images.src[i];
            if(images.description && jQuery.isArray(images.description)){
                obj.description = images.description[i];
            }
            params.images.push(obj);
        }*/
        for (var i = 0; i < params.list.length; i++) {
            if(params.validate && params.validate != ""){
                params.list[i].validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention != "" ){
                params.list[i].attention = validateGroupData(params.attention,i);
            }
        }
        return params;
    }
    /**
     * 多输入，多下拉，多下拉（数字型）
     */
    var multiData = function(params){
        for (var i = 0; i < params.list.length; i++) {
            if(params.validate && params.validate != ""){
                params.list[i].validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention != "" ){
                params.list[i].attention = validateGroupData(params.attention,i);
            }
        }
        return params;
    }
    /**
     * question_imagesTextarea题型 数据处理
     */
    var imagesTextareaData = function(params){
        params.images = [];
        var images = {
            src: ["http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/department/educationLogo/1498202450726.jpg","http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/department/educationLogo/1498202436459.jpg","http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/department/educationLogo/1498202425855.jpg"],
            description: ["原位","向上注视","向下注视"]
        };
        for (var i = 0; i < images.src.length; i++) {
            var obj = {};
            obj.src = images.src[i];
            if(images.description && jQuery.isArray(images.description)){
                obj.description = images.description[i];
            }
            params.images.push(obj);
        }
        return params;
    }
    /**
     * question_multiLabelTextData题型 数据处理
     */
    var multiLabelTextData = function(params){
        params.list = [];
        var length = params.label.length;
        for (var i = 0; i < length; i++) {
            var obj = {};
            obj.label = params.label[i];
            obj.placeHolder = params.placeHolder[i];
            obj.width = 100 / length + '%';
            if(params.validate && params.validate != ""){
                obj.validate = validateGroupData(params.validate,i);
            }
            if(params.attention && params.attention != "" ){
                obj.attention = validateGroupData(params.attention,i);
            }
            params.list.push(obj);
        }
        return params;
    }
    /**
     * 静态年龄/纠正年龄/纠正胎龄（）
     */
    var staticAgeData = function(params){
        params.effectId = params.id;
        params.id = params.id[0];
        return params;
    }
	/**
	 * 问卷数据处理
	 */
    var formatData = function(list,values,status,showIcon,showLabel){
		var arr = [];
		for(var i=0;i<list.length;i++){
			arr[i] = list[i];
            if (arr[i].id && arr[i].id instanceof Array) {
                if(arr[i].type == "question_gestationComplex"){    // gestationComplex 题型
                    arr[i].children = gestationComplexData(arr[i]);
                }else if(arr[i].type == "question_gestationSimple"){    // gestationSimple 题型
                    arr[i].children = gestationSimpleData(arr[i]);
                }else if(arr[i].type == "question_growthComplex" || arr[i].type == "question_growthSimple"){    // growthComplex、growthSimple 题型
                    arr[i].children = growthComplexData(arr[i]);
                }else if(arr[i].type == "question_radioInput"){
                    arr[i].children = radioInputData(arr[i]);
                }else if(arr[i].type == "question_checkboxInput"){
                    arr[i].children = checkboxInputData(arr[i]);
                }else if(arr[i].type == "question_correctAge"){
                    arr[i].children = correctAgeData(arr[i]);
                }else if(arr[i].type == "question_overallBirth"){
                    arr[i].children = overallBirthData(arr[i]);
                }else if(arr[i].type == "question_staticAge" || arr[i].type == "question_staticGestationalAge"){
                    arr[i] = staticAgeData(arr[i]);
                }
            }else if(arr[i].type == "question_address"){
                arr[i] = addressData(arr[i]);
            }else if(arr[i].type == "question_imagesMultiText"){
                arr[i] = imagesMultiTextData(arr[i]);
            }else if(arr[i].type == "question_multiSelectNumber" || arr[i].type == "question_multiSelect" || arr[i].type == "question_multiText" || arr[i].type == "question_multiTextSelect"){
                arr[i] = multiData(arr[i]);
            }else if(arr[i].type == "question_imagesTextarea"){
                //arr[i] = imagesTextareaData(arr[i]);  // ??? 暂时模拟用报文配置
            }else if(arr[i].type == "question_multiLabelText"){
                arr[i] = multiLabelTextData(arr[i]);
            }else if(arr[i].type == "question_imageProcessing"){
                if(arr[i].deviceTypeId){
                    arr[i].deviceTypeId = JSON.stringify(arr[i].deviceTypeId)
                }
                if(arr[i].diseaseTypeId){
                    arr[i].diseaseTypeId = JSON.stringify(arr[i].diseaseTypeId)
                }
                if(arr[i].manualTypeId){
                    arr[i].manualTypeId = JSON.stringify(arr[i].manualTypeId)
                }
            }else if(arr[i].type == "question_geneFusion"){
                arr[i].configParams = JSON.stringify(arr[i]);
            }
            if(typeof arr[i].validate == "object"){ // 数组、string、undefined（当是数组时，转化为string）
                arr[i].validate = JSON.stringify(arr[i].validate);
            }
            if(typeof arr[i].attention == "object"){
                arr[i].attention = JSON.stringify(arr[i].attention);
            }
			arr[i].status = status;
            if(arr[i].type == "qusetion_groupCollapse"){
                if(!arr[i].collapse){
                    arr[i].collapse = "false";
                }
            }
            if(arr[i].type == "question_date"){
                if(!arr[i].timeLimit){ arr[i].timeLimit = "no"; }
                var curTime = $comm.getCurTime().date;
                if( arr[i].timeLimit == "afterNow"){
                    arr[i].min = curTime;
                }else if( arr[i].timeLimit == "beforeNow" ){
                    arr[i].max = curTime;
                }
                if(arr[i].val && arr[i].val == "today") arr[i].val = curTime;
            }
			if(!arr[i].showIcon && showIcon){	// 为了一组问卷的图标icon是否显示
				arr[i].showIcon = showIcon;
			}
			if(!arr[i].length){
				arr[i].length = 4;
			}
			if(typeof arr[i].labelLength == "undefined"){  // 配置报文时，若没有配labelLength，默认为6
				arr[i].labelLength = 6;
			}
            if(arr[i].id){
               arr[i].name = arr[i].id; 
           }
            if(arr[i].calcType && arr[i].calcType == "00001" && arr[i].unit == "g"){  // 体重因为单位不统一，需要处理
                arr[i].name = arr[i].id + "-" + arr[i].unit;
            }
            // 为了随访悬浮nav锚点
            if( arr[i].type == "qusetion_groupCollapse" || arr[i].type == "qusetion_group" || arr[i].type == "qusetion_groupTable" ){
                if( !arr[i].id ) arr[i].id = "anchor_" + $comm.random(); 
            }
            if( arr[i].showLabel && showLabel && showLabel == "0" ){ // 除了最外层的组，其余内嵌的组都不显示label
                arr[i].showLabel = false;
            }
			if(arr[i].children){
                if(arr[i].relationId){
                    for (var j = 0; j < arr[i].children.length; j++) {
                        var data = {"relationId":arr[i].relationId};
                        $.extend(data,arr[i].children[j]);
                        $.extend(arr[i].children[j],data);
                    }
                }
				arr[i].children = formatData(arr[i].children,values,arr[i].status,null,"0");// "0":代表不显示label
			}else{
                if(arr[i].type=="question_tableInput"){
                    for (var p = 0; p < arr[i].tabledList.length; p++) {
                        for(var q = 0; q < arr[i].tabledList[p].rowData.length; q++){
                            arr[i].tabledList[p].rowData[q].validate = JSON.stringify(arr[i].tabledList[p].rowData[q].validate);
                            arr[i].tabledList[p].rowData[q].attention = JSON.stringify(arr[i].tabledList[p].rowData[q].attention);
                            if( values && values[arr[i].tabledList[p].rowData[q].id] ){
                                arr[i].tabledList[p].rowData[q].val = values[arr[i].tabledList[p].rowData[q].id];
                            }
                        }
                    }
                }
				if(values && ( values[arr[i].id] || values[arr[i].id]=="" ) ){
                    arr[i].val = values[arr[i].id]; // 字符串
                    if( values[arr[i].id] != "" &&arr[i].calcType && arr[i].calcType == "00001"){  // 体重因为单位不统一，需要处理
                        if(arr[i].unit && arr[i].unit == "g"){
                            var n = $comm.getDecimalPlaces(values[arr[i].id])-3;
                            if(n < 0) n = 0;
                            arr[i].val = (values[arr[i].id]*1000).toFixed(n);
                        }
                    }
				}
			}
			switch (arr[i].type) {
    			case "question_radio":
    			case "question_select":
    			case "question_checkbox":
                case "question_checkboxWithInput":
                case "question_radioWithInput":
                case "question_checkboxRelation":
                case "question_radioRelation":
                case "question_multiSelectNumber":
                case "question_multiSelect":
                case "question_multiText":
                case "question_multiTextSelect":
                case "question_address":
                case "question_multiLabelText":
                case "question_imagesMultiText":
                case "question_imagesTextarea":  // ??模拟图片时 临时用的
                    // ??模拟图片时 临时用的
                    if(arr[i].type=="question_imagesMultiText" || arr[i].type=="question_imagesTextarea"){
                        if(arr[i].images && arr[i].images.length > 0){
                            for (var j = 0; j< arr[i].images.length; j++) {
                                arr[i].images[j].width = (100 / arr[i].images.length - 1) + '%';
                            }
                        }
                    }
    				if(arr[i].list&&arr[i].list.length>0){
    					if(arr[i].type=="question_checkbox" || arr[i].type=="question_radioWithInput" || arr[i].type=="question_checkboxWithInput" || arr[i].type=="question_checkboxRelation" || arr[i].type=="question_multiSelectNumber" || arr[i].type=="question_multiSelect" || arr[i].type=="question_multiText" || arr[i].type=="question_address" || arr[i].type=="question_imagesMultiText" || arr[i].type=="question_multiLabelText" || arr[i].type=="question_multiTextSelect"){   // 复选框、多下拉框（num）、多下拉框、多输入框、地址（value值是数组）
    						if(arr[i].val && typeof(arr[i].val) == "string"){
    							arr[i].val = JSON.parse(arr[i].val);
    						}
    					}
                        if( arr[i].type=="question_multiSelectNumber" || arr[i].type=="question_multiSelect" || arr[i].type=="question_multiText" || arr[i].type=="question_address" || arr[i].type=="question_imagesMultiText"){
                            for (var j = 0; j < arr[i].list.length; j++) {
                                arr[i].list[j].width = 100 / arr[i].list.length + '%';
                                arr[i].list[j].textWidth = Number(arr[i].list[j].subunit.length) + Number(1) + 'em';
                                if( arr[i].val && arr[i].val instanceof Array){
                                    arr[i].list[j].val = arr[i].val[j];
                                }
                            }
                        }else if( arr[i].type=="question_multiTextSelect" ){
                            for (var j = 0; j < arr[i].list.length; j++) {
                                arr[i].list[j].width = 100 / arr[i].list.length + '%';
                                if( arr[i].val && arr[i].val instanceof Array){
                                    arr[i].list[j].val1 = arr[i].val[2*j];
                                    arr[i].list[j].val2 = arr[i].val[2*j+1];
                                }
                            }
                        }else if(arr[i].type=="question_multiLabelText"){
                            for (var j = 0; j < arr[i].list.length; j++) {
                                if( arr[i].val && arr[i].val instanceof Array){
                                    arr[i].list[j].val = arr[i].val[j];
                                }
                            }
                        }else if(arr[i].type=="question_checkboxWithInput"){
                            if(typeof(arr[i].list[0]) == "string"){
                                for (var j = 0; j < arr[i].list.length; j++) {
                                    var str = arr[i].list[j];
                                        arr[i].list[j] = {};
                                        arr[i].list[j].key = str;   // 字符串
                                        arr[i].list[j].text = str;   // 字符串
                                        arr[i].list[j].flag = false; // 标志有没有选中 默认为未选中
                                    if(arr[i].val && arr[i].val instanceof Array){
                                        for(var p = 0; p < arr[i].val.length; p++){
                                            if(arr[i].list[j].key == arr[i].val[p]){
                                                arr[i].list[j].flag = true;
                                                break;
                                            }
                                            // 判断arr[i].val里的最后一个在不在list里，不在的话即为输入框里的数据
                                            var lastVal = arr[i].val[arr[i].val.length-1];
                                            var result = $.inArray(lastVal,arr[i].list);
                                            if(result == -1){ // 复选框+输入框数据（数组最后一个是输入框数据）
                                                arr[i].valText = lastVal; 
                                            }
                                        }
                                    }
                                }
                            }
                        }else if(arr[i].type=="question_radioWithInput"){
                            if(typeof(arr[i].list[0]) == "string"){
                                for (var j = 0; j < arr[i].list.length; j++) {
                                    var str = arr[i].list[j];
                                        arr[i].list[j] = {};
                                        arr[i].list[j].key = str;   // 字符串
                                        arr[i].list[j].text = str;   // 字符串
                                        arr[i].list[j].flag = false; // 标志有没有选中 默认为未选中
                                    if(arr[i].val && arr[i].val instanceof Array){
                                        if(arr[i].list[j].key == arr[i].val[0]){
                                            arr[i].list[j].flag = true;
                                        }
                                        if(arr[i].val.length > 1){
                                            arr[i].valText = arr[i].val[1];
                                        }
                                    }
                                }
                            }
                        }else{
        					if(typeof(arr[i].list[0]) == "string"){
        						for(var j=0;j<arr[i].list.length;j++){
        							var str = arr[i].list[j];
        							arr[i].list[j] = {};
                                    arr[i].list[j].key = str;   // 字符串
        							arr[i].list[j].text = str;   // 字符串
        							arr[i].list[j].flag = false; // 标志有没有选中 默认为未选中
                                    if(arr[i].type == "question_checkboxRelation" || arr[i].type == "question_radioRelation"){
                                        for (var q = 0; q < arr[i].relation.length; q++) {
                                            if( arr[i].relation[q].relationKey == arr[i].list[j].key){
                                                arr[i].list[j].relationId = arr[i].relation[q].relationId;
                                                break;
                                            }
                                        }                                    
                                    }
        							if(arr[i].val && arr[i].val.length > 0){
        								if(typeof(arr[i].val[0]) == "string"){
        									if(arr[i].type=="question_checkbox" || arr[i].type=="question_checkboxRelation"){
        										for(var p = 0; p < arr[i].val.length; p++){
        											if(arr[i].list[j].key == arr[i].val[p]){
        												arr[i].list[j].flag = true;
        												break;
        											}
        										}
        									}else{
        										if(arr[i].list[j].key == arr[i].val){
        											arr[i].list[j].flag = true;
        										}
        									}
        								}
        							}
        						}
        					}
                        }
    				}
    				break;
                case "question_staticFormat":
                    if(arr[i].val && arr[i].val.indexOf("[") != -1 && arr[i].val.indexOf("]") != -1){ arr[i].val = JSON.parse(arr[i].val); }
                    if(arr[i].val instanceof Array){
                        var str = arr[i].formatShow; //eg:"[0]周[1]天"
                        var reg = /\[\d+]/;
                        for (var j = 0; j < arr[i].val.length; j++) {
                            str = str.replace(reg,arr[i].val[j]);
                        }
                        if(str.indexOf("[") != -1){ // question_checkbox、question_checkboxWithInput
                            var index = str.indexOf("[");
                            var str = str.substring(0,index);
                        }
                        arr[i].val = str;
                    }            
                    break;
                case "question_staticAge":
                case "question_staticGestationalAge":
                    if(values && values[arr[i].effectId[0]]){
                        var presentDate = $comm.getCurTime().date;
                        var bothDate = values[arr[i].effectId[0]];
                        var dueDate = values[arr[i].effectId[1]] == "" ? bothDate : values[arr[i].effectId[1]];
                        var gestation = $comm.getGestation(bothDate,dueDate);
                        var daysGestation = gestation.weekActual*7 + gestation.dayActual; // 孕周（单位天）
                        if (arr[i].effectId.length == 3){
                            if( values[arr[i].effectId[2]] != "" ){
                                var arrGestation = JSON.parse(values[arr[i].effectId[2]]);
                                daysGestation = arrGestation[0]*7 + arrGestation[1];
                            }
                        }
                        var actualDays = $comm.dateDiff(bothDate,presentDate).days;
                        var correctDays = $comm.dateDiff(dueDate,presentDate).days;
                        var days;
                        if( arr[i].type == "question_staticAge" ){
                            if(daysGestation < 37*7 && actualDays < 365*2){
                                if(correctDays < 0){
                                    days = correctDays + 40*7;
                                    arr[i].label = "纠正胎龄";
                                }else{
                                    days = correctDays;
                                    arr[i].label = "纠正年龄";
                                }
                            }else{
                                days = actualDays;
                                arr[i].label = "年龄";
                            }
                            arr[i].val = $comm.formatAge(days);
                        }else if( arr[i].type == "question_staticGestationalAge" ){
                            if(daysGestation < 37*7 && actualDays < 365*2){
                                days = correctDays + 40*7;
                                arr[i].label = "矫正胎龄";
                            }else{
                                days = actualDays;
                                arr[i].label = "年龄";
                            }
                            arr[i].val = $comm.formatAge(days);
                        }
                    }
                    break;
                case "question_staticAtualAge":
                    if ( arr[i].val && arr[i].val.match(/^((?!0000)[0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/) ){ 
                        var curTime = $comm.getCurTime().date;
                        var age = $comm.dateDiff(arr[i].val,curTime).age;
                        arr[i].val = age;
                    }
                    break;
                case "question_uploadPictures":
                    if( arr[i].val) arr[i].val = JSON.parse(arr[i].val);
                    break;
                case "question_sudoku":
                    if(typeof(arr[i].list[0]) == "string"){
                        for(var j = 0; j < arr[i].list.length; j++){
                            var str = arr[i].list[j];
                            arr[i].list[j] = {};
                            arr[i].list[j].key = str;   // 字符串
                            arr[i].list[j].text = str;   // 字符串
                            arr[i].list[j].flag = false; // 标志有没有选中 默认为未选中
                            arr[i].list[j].clickable = true;
                            if(arr[i].list[j].key == arr[i].val){
                                arr[i].list[j].flag = true;
                            }
                        }
                        if(arr[i].list.length % 3 != 0){
                            var num = 3 - arr[i].list.length % 3;
                            var obj = {
                                "key":"",
                                "text":"",
                                "flag":false,
                                "clickable":false,
                            }
                            for (var j = 0; j < num; j++) {
                                arr[i].list.push(obj);
                            }
                            
                        }
                    }
                    break;
    			default:
    				break;
			}
		}
		return arr;
	}
   
	/**
	 * 获取处理完的问卷数据
	 */
	servers.getQuestionData = function(options){
		var defaults = {
			status:"default",
			showIcon: false
		};
		var opts = $.extend(defaults, options);
		if(opts.list && jQuery.isArray(opts.list)){	// 配置了问卷的情况
			var arr = [];
			for(var k = 0; k < opts.list.length; k++){
				arr.push(formatData(opts.list[k],opts.values,opts.status,opts.showIcon));
			}
		}
		var data = {
			questions: arr,	// 问卷
		};
		return data;
	}
	//为jquery.serializeArray()解决radio,checkbox未选中时没有序列化的问题
    $.fn.ghostsf_serialize = function(){
        var arr = this.serializeArray();
        var $box = $('input[type=radio],input[type=checkbox]', this);
        var temp = {};
        $.each($box, function () {
            if (!temp.hasOwnProperty(this.name)) {
                if ($("input[name='" + this.name + "']:checked").length == 0) {
                    temp[this.name] = "";
                    arr.push({name: this.name, value: ""});

                }
            }
        });
        return arr;
    };
    /**
     * 保存时，复选框、多下拉框值的特殊处理
     */
    var getArrKey = function(dom){ // 复选框、多下拉框的id，name值的集合
        var arrKey =[];   
        dom.map(function(){
            var key = $(this).attr("name");
            if(0 == arrKey.length){
                arrKey.push(key);
            }
            var flkey = "0";
            for (var i = 0; i < arrKey.length; i++) {
                if(arrKey[i] == key){
                    flkey = "1";
                    break;
                }
            }
            if(flkey == "0"){
                arrKey.push(key);
            }
        });
        return arrKey;
    }
    var handleCheckbox = function(dom,data,list){   // 复选框的特殊处理
        var arrKey = getArrKey(dom);
        for (var i = 0; i < arrKey.length; i++) {
            var arr =[];
            for(var j=0;j<list.length;j++){
                if(arrKey[i] == list[j].name){
                    arr.push(list[j].value);
                }
            }
            data[arrKey[i]] = JSON.stringify(arr);
        }  
    }
    var handleMultiple = function(dom,data,list){  // 多下拉框、多输入框值的特殊处理
        var arrKey = getArrKey(dom);
        for (var i = 0; i < arrKey.length; i++) {
            var arr =[];
            for(var j=0;j<list.length;j++){
                if(arrKey[i] == list[j].name){
                    arr.push(list[j].value);
                }
            }
            data[arrKey[i]] = JSON.stringify(arr);
        }
    }
    var handleMultipleNum = function(dom,data,list){  // 多下拉框number类型
        var arrKey = getArrKey(dom);
        for (var i = 0; i < arrKey.length; i++) {
            var arr =[];
            for(var j=0;j<list.length;j++){
                if(arrKey[i] == list[j].name){
                    arr.push(Number(list[j].value));
                }
            }
            data[arrKey[i]] = JSON.stringify(arr);
        }
    }
    var handleRadioWithInput = function(dom,data,list){
        var arrKey = getArrKey(dom);
        for (var i = 0; i < arrKey.length; i++) {
            var arr =[];
            for(var j=0;j<list.length;j++){
                if(arrKey[i] == list[j].name){
                    arr.push(list[j].value);
                }
            }
            data[arrKey[i]] = JSON.stringify(arr);
        }  
    }
    var handlePictureUrl = function(dom,data){
        dom.each(function(i){
            var arr = [];
            var id = dom.eq(i).children(".qaCard-uploadBtn").children("input[type=file]").attr("name");
            var $picture = dom.eq(i).children(".picture");
            $picture.each(function(j){
                var value = $picture.eq(j).attr("data-value");
                arr.push(value);
            });
            data[id] = JSON.stringify(arr);
        });
    }
    //影像编辑：提交保存的数据；
    var handleImageProcessing = function(dom,data){
        dom.each(function(i){
            var arr = [];
            var id = dom.eq(i).children(".imageProcessing-addBtn").attr("name");
            var $picture = dom.eq(i).children(".qaCard-imageBox").children(".picture");
            $picture.each(function(j){
                var imgId = $picture.eq(j).attr("imgId");
                var imgUrl = $picture.eq(j).attr("imgOldUrl");
                var markIdList = $picture.eq(j).attr("markIdList") ? JSON.parse($picture.eq(j).attr("markIdList")):"";
                arr.push({
                    "imgId":imgId,
                    "markIdList":markIdList,
                    "imgUrl":imgUrl
                });
            });
            data[id] = JSON.stringify({"imageEdit":arr}); //imageEdit:用来分辨是否是影像编辑的信息；
        });
    }
    /**
	 * 问卷答案提交前的处理
	 */
    servers.getDataForDom = function(domId){    // 表单id
        var data = {};       
        var list = $("#"+domId).ghostsf_serialize();
        handleCheckbox($("#"+domId+" [type='checkbox']:checked"),data,list);  // 复选框
        handleMultipleNum($("#"+domId+" .multiple select.mul-num"),data,list); // 多下拉框(number类型)
        handleMultiple($("#"+domId+" .multiple select.mul-str"),data,list); // 多下拉框
        handleMultiple($("#"+domId+" .multiple input"),data,list); // 多输入框
        handleMultiple($("#"+domId+" .qaCard-multiLabelText input"),data,list); // 多label输入框
        handleRadioWithInput($("#"+domId+" .qaCard-radioWithInput .radio input[type='radio']:checked,#"+domId+" .qaCard-radioWithInput .qaCard-radioWithInput-input input[type='text']"),data,list);  // 复选框
        handlePictureUrl($("#"+domId+" .qaCard-pictures"),data); // 处理图片地址
        handleMultiple($("#"+domId+" .multi-text-select .form-control"),data,list); // 多(输入框+下拉框）
        handleMultiple($("#"+domId+" .string-change-arr .form-control"),data,list); // 多(输入框+下拉框）

        //图片编辑
        handleImageProcessing($("#"+domId+" .qaCard-imageProcessing "),data); // 处理图片信息

        for(var i=0;i<list.length;i++){
            if(!data[list[i].name]){
                if( list[i].name.indexOf("-") > -1 ){   // 单独处理体重单位（kg与g）
                    var unitArr = list[i].name.split("-");
                    if(unitArr[1]=="g"){
                        if(list[i].value){
                            var n = $comm.getDecimalPlaces(list[i].value)+3;
                            list[i].value = (list[i].value / 1000).toFixed(n).toString();
                        }
                    }
                    data[unitArr[0]] = list[i].value;
                }else{
                    data[list[i].name] = list[i].value;
                }
            }
        }
        return data;
    }
	/**
	 * 生长曲线数据处理(每一条)
	 */
    var growthCurveNormData = function(data,max,min, name, color){
    	var arr = [];
        var lens = data.length;
        var len = (max - min) / lens;
        arr[0] = [0, data[0]];
        for(var i = 0; i < lens; i++){
           if(i == lens-1 ){
                var lastData = {
                    value: [len*(i+1)+min, data[i]],
                    label : {
                        normal:{
                            show: true,
                            position: "insideBottomLeft",
                            textStyle : {
                                color:color,
                                fontSize:"8"
                            },
                            formatter: name                        
                        }
                    },
                };
                arr[i+1] = lastData;
           }else{
                arr[i+1] = [len*(i+1)+min, data[i]];
           }
       	}
        return arr;
    }
    /**
     * 患者传入记录值数据处理
     */
    var growthCurvePresentData = function(data){
        var arr = [];
        for(var i = 0; i < data.length; i++){
            if(data[i].flag == "1"){
                var recentGrowthRecord = {
                    value: [data[i].xDate, data[i].yDate],
                    symbol: 'circle',
                    symbolSize : 20,
                    itemStyle: {        // 数据级个性化折线样式
                        normal: {
                            color: 'yellowgreen',
                        },
                        emphasis: {
                            color: 'orange',
                            label : {
                                show: true,
                                position: 'inside',
                                textStyle : {
                                    fontSize : '18'
                                }
                            }
                        }
                    }
                };
                arr.push(recentGrowthRecord);
            }else{
                arr.push([data[i].xDate, data[i].yDate]);
            }
        }
        return arr;
    }
	/**
	 * 生长曲线数据处理(整体)
	 */
    var GrowthCurveTotalData = function(data,label){
        var obj = {};
        obj.xMax = data.xMax;
        obj.xMin = data.xMin;
        obj.yMax = data.yMax;
        obj.yMin = data.yMin;
        var len = parseInt((obj.yMax - obj.yMin) / 25);		// 自定义y轴间距
        for (var i = 0; i <= len; i++) {
        	if(i == len){
        		obj.interval = i+1;
        	}
        }
        if(data.timeUnit == "周"){							// x轴名称
            obj.xName = "周龄（0-"+ data.xMax +"周)";
            obj.timeUnit = "周";
        }else if(data.timeUnit == "月"){
            obj.xName = "月龄（0-"+ data.xMax +"月)";
            obj.timeUnit = "月";
        }else if(data.timeUnit == "年"){
            obj.xName = "年龄（0-"+ data.xMax +"岁)";
            obj.timeUnit = "年";
        }
        obj.yName = label.replace(/\(g\)/,"(kg)");			// y轴名称
        /* 曲线数组 */
        var numArr = [0,1,1,2,2,3,3];  // 线的颜色下标
        var colors = ['#00843d','#ff860d','#e41836','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
        var nameArr = ["50%","75%","25%","90%","10%","97%","3%"];
        var dataSDArr = [data.SD0,data.SD1,data.SD1eng,data.SD2,data.SD2eng,data.SD3,data.SD3eng];
        var sdArr = [];
        for(var i=0; i<dataSDArr.length; i++){
            sdArr[i] = {
                "num" : numArr[i],
                "name" : nameArr[i],
                "sd" : growthCurveNormData(dataSDArr[i], data.xMax, data.xMin, nameArr[i], colors[numArr[i]])
            }
        }
        obj.sd = sdArr;
        obj.grownRecord = growthCurvePresentData(data.growthrecord);
        return obj;
    }
    /**
     * 曲线图中转换年龄
     */
    var converAge = function(timeUnit,value0,value1,label){
        var allDays;
        if(timeUnit ==="周"){
            allDays = value0*7;
            var weeks = Math.floor(allDays/7);
            var days = Math.round(allDays%7);
            var age = weeks + "周" + days + "天";
        }else if(timeUnit=="月"){
            allDays = value0*30.4;
            var months = Math.floor(allDays/30.4);
            var weeks = Math.floor(allDays%30.4/7);
            var days = Math.round(allDays%7);
            var age = months + "月" + weeks + "周" + days + "天";
        }else if(timeUnit=="年"){
            allDays = value0*365;
            var years = Math.floor(allDays/365);
            var months = Math.floor(allDays%365/30.4);
            var weeks = Math.floor(allDays%365%30.4/7);
            var days = Math.round(allDays%365%30.4%7);
            var age = years + "年" + months + "月" + weeks + "周" + days + "天";
        }
        var labelUnit = label.split("(");
        var unit = labelUnit[1].split(")")[0];
        if (unit == "g") {
            unit = "kg";
        }
        var str = timeUnit+"龄：" + age + "<br />" + 
                  labelUnit[0] + "：" + value1 + unit +"<br />";
        return str;
    }
    /**
     * 曲线图中数据参数
     */
    var seriesParams = function(data){
        var colors = ['#00843d','#ff860d','#e41836','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
        var series = [];
        for (var i = 0; i < data.sd.length; i++) {
            series.push({
                name: data.sd[i].name,
                type: 'line',
                smooth:"true",
                symbol:'circle',
                hoverAnimation:false,
                data: data.sd[i].sd,
                itemStyle: {
                    normal: {
                        color: "transparent",
                        lineStyle: {
                            color: colors[data.sd[i].num]
                        },
                    }
                }
            });
        };
        series.push({
            name: 'baby',
            type: 'scatter',
            data:data.grownRecord,
            symbol:'circle',
            symbolSize:'10',
            itemStyle: {
                normal: {
                    color:  "green",
                    lineStyle: {
                        color: 'green'
                    }
                }
            }
        });
        return series;
    }
    /**
     * growth曲线图的参数
     */
    var growthCurveOption = function(curvedata,label,interval,gender){
        var sexColor = gender == 'F' ? "#e47db2":"#0596d5";
        var data = GrowthCurveTotalData(curvedata,label);
    	var option = {
        	backgroundColor: sexColor, //背景色
            textStyle: {
                fontSize: "15px",
                color:"#fff"
            },
            tooltip: {
                trigger: 'item',
                formatter: function (params) {
                    if(params.seriesName == "baby"){
                        var str = converAge(data.timeUnit,params.value[0],params.value[1],label);
                    }else{
                        var str = params.seriesName + ":" + params.value[1] + "<br />";
                    }                 
                    return str;
                }
            },
            legend: {
                data: []
            },
            grid: {
                left: '4%',
                right: '6%',
                bottom: '6%',
                top:'3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                name:data.xName,
                nameLocation:"middle",
                nameGap:"28",
                scale:true,
                boundaryGap: false,
                splitLine:{show: true},//去除网格线
                splitArea : {show : false},//保留网格区域
                min:data.xMin,
                max:data.xMax,
                interval:interval,
                axisLine: {
                    lineStyle: {
                        color: "#8e7f8a"
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    }
                },
                axisTick: {
                    show: false,
                    alignWithLabel: false,
                    interval: 'auto',
                    inside: true
                }
            },
            yAxis:{
                type: 'value',
                min:data.yMin,
                max:data.yMax,
                interval:data.interval,
                name:data.yName,
                nameLocation:"middle",
                nameGap:"28",
                splitLine:{
                    show: true//保留网格线
                },
                splitArea : {
                    show :true,//保留网格区域
                    areaStyle:{
                        color:"#fff"
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: "#8e7f8a"
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: "#fff"
                    }
                },
                axisTick: {
                    show: false,
                    alignWithLabel: false,
                    inside: true
                }
            },
            series: seriesParams(data),
        };
        return option;
    }
    /**
     * fenton数据（给线加name和trendname，如："97%"、"体重"）
     */
    var trendsNameDeal = function(data,name,trendname,color){
        var len = data.length;
        data[len-24]={
            value: data[len-24],
            label : {
                normal:{
                    show: true,
                    position: "top",
                    textStyle : {
                        color:color,
                        fontSize:"4"
                    },
                    formatter:name
                }
            },
        }
        if(name=="97%" || name=="3"){
            data[len-55]={
                value: data[len-55],
                label : {
                    normal:{
                        show: true,
                        position: 'top',
                        textStyle : {
                            color:"#333",
                            fontSize:"8"
                        },
                        formatter:trendname
                    }
                },
            }
        }
        return data;
    }
    /**
     * fenton数据（点数据）记录处理
     */
    var growthRecordDeal = function(data){
        var initArr = {
            "history":[],
            'nowFlag':[]
        };
        var color = ["#0596d5","#e47db2","#ff8400"];//0,男；1，女；3，橙色
        var list = data.growthrecord;
        for( var i = 0; i < list.length; i++ ){
            if( list[i].result ) {
                if (data.scoreType == "01") {
                    // var result = JSON.parse(list[i].result)[0].percentileRange;  // 可以直接用这行代替下面的判断
                    if(typeof list[i].result == "string"){
                        var result = JSON.parse(list[i].result)[0].percentileRange;
                    }else{
                        var result = list[i].result[0].percentileRange;
                    }

                    if(data.curveType == "02"){
                        if (result.indexOf("~") != "-1") {
                           var sexColor = data.sex == "男" ? color[0] : color[1];
                        }else{
                           var sexColor = color[2];
                        }
                    }
                }
            }
            var fentonRecord = {
                value: [list[i].xDate,list[i].yDate],
                itemStyle: {
                    normal:{
                        color:sexColor
                    },
                    emphasis: {
                        color: sexColor
                    }
                }
            };
            initArr.history.push(fentonRecord);
            if(list[i].flag == "1" || list[i].flag == 1){ // list[i].flag == "1"可以删掉
                initArr.nowFlag = [list[i].xDate,list[i].yDate,sexColor];
            }
        }
        return initArr;
    };
    /**
     * fenton曲线数据处理
     */
    var fentonData = function(data,sexColor,gender){
        var fentonRes = {};
        var keyName = ["weight","height","head"];
        var keyName2, lineType, lineColor;
        if(data.scoreType == "01"){
            keyName2 = ['50%','10%','90%','3%','97%','baby'];
            lineType = ['solid','dashed','dashed','dotted','dotted'];
            lineColor=['#00612d','#00b0c8','#00b0c8','#ff8400','#ff8400'];
            for( var i = 0; i < data.curvadataList.length; i++ ){
                if( data.curvadataList[i].type == '0000'+(i+1) ){
                    fentonRes[keyName[i]] = [];
                    fentonRes[keyName[i]][0] = data.curvadataList[i].curvedata.SD0,
                    fentonRes[keyName[i]][1] = data.curvadataList[i].curvedata.SD2eng,
                    fentonRes[keyName[i]][2] = data.curvadataList[i].curvedata.SD2,
                    fentonRes[keyName[i]][3] = data.curvadataList[i].curvedata.SD3eng,
                    fentonRes[keyName[i]][4] = data.curvadataList[i].curvedata.SD3,
                    fentonRes[keyName[i]][5] = data.curvadataList[i].curvedata.growthrecord
                }
            }
        }else if(data.scoreType == "02"){
            keyName2 = ['0','-1','1','-2','2','-3','3','baby'];
            lineType = ['solid','solid','solid','solid','solid','solid','solid'];
            lineColor = ['#00612d','#ffb13d','#ffb13d','#e41836','#e41836','#252122','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
            for( var i = 0; i < data.curvadataList.length; i++ ){
                if( data.curvadataList[i].type == '0000'+(i+1) ){
                    fentonRes[keyName[i]] = [];
                    fentonRes[keyName[i]][0] = data.curvadataList[i].curvedata.SD0,
                    fentonRes[keyName[i]][1] = data.curvadataList[i].curvedata.SD1eng,
                    fentonRes[keyName[i]][2] = data.curvadataList[i].curvedata.SD1,
                    fentonRes[keyName[i]][3] = data.curvadataList[i].curvedata.SD2eng,
                    fentonRes[keyName[i]][4] = data.curvadataList[i].curvedata.SD2,
                    fentonRes[keyName[i]][5] = data.curvadataList[i].curvedata.SD3eng,
                    fentonRes[keyName[i]][6] = data.curvadataList[i].curvedata.SD3,
                    fentonRes[keyName[i]][7] = data.curvadataList[i].curvedata.growthrecord
                }
            }
        }
        var series = [];
        for(var key in fentonRes){
            var name, yAxisIndex, type;
            name = key == 'height' ? "身长" : key == 'weight' ? "体重" : key == 'head' ? "头围" : "baby";
            yAxisIndex = key == 'weight' ? 0 : 1;
            for( var i = 0; i < fentonRes[key].length; i++ ){
                if( i == fentonRes[key].length-1 ){
                    var params = {
                        'growthrecord':fentonRes[key][i],
                        'sex':gender,
                        'scoreType':data.scoreType,
                        'curveType':data.curveType
                    };
                    var babyInit = growthRecordDeal(params);
                    babyInit.nowFlag[1] = key == 'weight'? parseFloat(babyInit.nowFlag[1]).toFixed(2) : parseFloat(babyInit.nowFlag[1]).toFixed(1);
                    var baby = {
                        name: name,
                        type: 'line',
                        data: babyInit.history,
                        symbol:'circle',
                        symbolSize:'6',
                        markPoint: {
                            itemStyle: {
                                normal: {
                                    color:babyInit.nowFlag[2]
                                }
                            },
                            data: [
                                {
                                    xAxis: babyInit.nowFlag[0],
                                    yAxis: babyInit.nowFlag[1] 
                                }
                            ]
                        },
                        itemStyle: {
                            normal: {
                                color: sexColor,
                                lineStyle:{
                                    width:1
                                }
                            },
                            emphasis:{
                                color: sexColor
                            }
                        },
                        yAxisIndex: yAxisIndex
                    }
                    series.push(baby);
                }else{
                    fentonRes[key][i] = trendsNameDeal(fentonRes[key][i],keyName2[i],name,lineColor[i]);
                    var trend = {
                        name: keyName2[i],
                        type: 'line',
                        smooth:"true",
                        symbol:'circle',
                        hoverAnimation:false,
                        itemStyle: {
                            normal: {
                                color: "transparent",
                                lineStyle: {
                                    color:lineColor[i],
                                    type:lineType[i],
                                    width:1
                                }
                            }
                        },
                        data: fentonRes[key][i],
                        yAxisIndex:yAxisIndex
                    }
                    series.push(trend);
                }
            }
        }
        series.push({
            type: 'line',
            smooth:"true",
            symbol:'circle',
            hoverAnimation:false,
            lineStyle: {
                normal: {
                    color:"#333",
                    type:"solid",
                    width:2
                }
            },
            data: [[40,-30],[40,60]]
        });
        return series;
    }
    /**
     * fenton曲线图的参数
     */
    var fentonCurveOption = function(data,gender){
        var sex = gender == 'F' ? "女":"男"; 
        var sexColor = gender == 'F' ? "#e47db2":"#0596d5";
        var series = fentonData(data,sexColor,sex);
        var option = {
            backgroundColor: sexColor, //背景色
            tooltip: {
                formatter: function( params, ticket, callback ) {
                    var val = "";
                    if(params.seriesName == "体重" || params.seriesName == "身长" || params.seriesName == "头围"){
                        if(params.componentType != "markPoint") {
                            var gestationAge = parseInt(params.data.value[0] / 7) + "周" + Math.round(params.data.value[0] % 7) + "天";
                            var value = params.seriesName == "体重" ? parseFloat(params.data.value[1]).toFixed(2) : parseFloat(params.data.value[1]).toFixed(1);
                            val += "胎龄：" + gestationAge + "<br/>" + params.seriesName + "：" + value;
                        }
                    }else{
                        var dataY = params.data instanceof Array ? params.data[1] : params.data.value[1];
                        val += params.seriesName +": "+ parseFloat(dataY).toFixed(3);
                    }
                    return val;
                }
            },
            grid: {
                left: '0%',
                right: '0%',
                bottom: '4%',
                top:'3%',
                containLabel: true
            },
            xAxis: {
                name: '胎龄（周）',
                nameLocation: 'middle',
                nameGap:"27",
                nameTextStyle: {color: "#fff"},
                max:50,
                min:22,
                interval:1,
                splitLine:{     //网格线
                    show: true,
                    lineStyle:{
                        color:["#333","#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc", "#333","#ccc","#ccc",
                                "#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc","#333","#ccc","#ccc","#ccc"]
                    }
                },
                splitArea : {show : false},//保留网格区域
                axisTick: {
                    show: true,
                    alignWithLabel: false,
                    interval: 'auto',
                    inside: true
                },
                axisLabel: {
                    textStyle: {
                        color: function(value){
                            if(value%2 != 0){
                                return "transparent";
                            }else{
                                return "#fff";
                            }
                        }
                    }
                },
            },
            yAxis: [
                {
                    name: '体重(kg)                                              厘米',
                    nameLocation: 'middle',
                    nameGap:"30",
                    nameTextStyle: {color: "#fff"},
                    max: 9,
                    min:0,
                    interval:0.1,
                    type: 'value',
                    splitLine:{
                        show: true//保留网格线
                    },
                    splitArea : {
                        show :true,//保留网格区域
                        areaStyle:{
                            color:"#fff"
                        }
                    },
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value > 4 ? "transparent" : value * 10 % 5 != 0 ? "transparent" : "#fff";
                            }
                        }
                    },
                },
                {
                    name:'体重(kg)                                              厘米',
                    nameLocation: 'middle',
                    nameGap:"27",
                    nameTextStyle: {color: "#fff"},
                    type: 'value',
                    max: 60,
                    min:-30,
                    interval:1,
                    splitLine:{
                        show: true//保留网格线
                    },
                    splitArea : {
                        show :true,//保留网格区域
                        areaStyle:{
                            color:"#fff"
                        }
                    },
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value < 40 ? "transparent" : value % 5 != 0 ? "transparent" : "#FFF";
                            }
                        }
                    }
                },
                {
                    position:'left',
                    type: 'value',
                    max: 60,
                    min:-30,
                    interval:1,
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return  value < 15 ? "transparent" : value % 5 != 0 ? "transparent" : "#FFF";
                            }
                        }
                    }
                },
                {
                    type: 'value',
                    position:'right',
                    max: 9,
                    min:0,
                    interval:0.1,
                    axisTick: {
                        inside: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: function(value,index){
                                return value > 6.5 ? "transparent" : value * 10 % 5 != 0 ? "transparent" : "#FFF";
                            }
                        }
                    },
                    splitLine:{
                        show: true,//保留网格线
                        lineStyle:{
                            color:["#333","#ccc","#ccc","#ccc","#ccc"],
                            width:1
                        }
                    }
                }
            ],
            animation:false,
            series:series
        };
        return option;
    }
    /**
     * 获取曲线图的参数
     */
    servers.curveOption = function(data,interval,label,gender){
        var option;
        if (data.scoreType == "01"){ // 百分位曲线
            if(data.curveType == "01"){ // growth曲线
                option = growthCurveOption(data.curvadataList[0].curvedata,label,interval,gender);
            }else if(data.curveType == "02"){  // fenton曲线
                option = fentonCurveOption(data,gender);
            }
        }
        return option;
    }
    /**
     * 根据手机号码查询患者
     */
    servers.ajaxPatientsByPhone = function(params,callback,obj,options){
        $bb.ajax({
            url: URL + "followup/service/patient/patientQueryByPhoneNum",
            data:JSON.stringify({
                data : params
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,params,obj,options);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "根据手机号码查找患者失败！");
                }
            }
        });
    }
    /**
     * 处理根据手机号码查询出来的患者数据
     */
    servers.handlePatientsByPhone = function(list){
        var arr = [];
        for(var i=0;i<list.length;i++){
            arr[i] = {};
            arr[i].userName = list[i].userName;
            arr[i].gender = list[i].gender;
            arr[i].ptSchemeId = list[i].ptSchemeId;
        }
        return arr;
    }

    /**
     * 获取评估题目
     */
    servers.getAssessQuest = function(params,callback){
        $bb.ajax({
            url: URL + "followup/service/patient/evaluation/getAllPostion",
            data:JSON.stringify({
                data : {
                    "userId":params.userId,
                    "examinationPaperName":params.examinationPaperName
                }
            }),
            success: function(data){
                if(data.success){ 
                    $bb.ajax({
                        url: URL + "followup/service/patient/evaluation/getHistoryScore",
                        data:JSON.stringify({
                            data : {
                                "userId":params.userId,
                                "taskId":params.taskId,
                                "examinationPaperName":params.examinationPaperName
                            }
                        }),
                        success: function(req){
                            if(req.success){ 
                                var lastScore = req.rows.length > 0 ? req.rows[0] : null;
                                callback(data.data,params,lastScore);
                            }else{
                                $bb.toastShow(data.msg ? data.msg : "查询评估记录出错！");
                            }
                        }
                    });
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询评估题目出错！");
                }
            }
        });
    }
    /**
     * 将获取的评估题目进行数据处理(高危儿孕产妇)
     */
    servers.highriskPregnantData = function(data,lastScore){
        var arr = [];
        for( var key in data){
            var obj = {
                "label":key,
                'list':data[key]
            };
            arr.push(obj);
        }
        if(lastScore != null){
            var idResultArr = JSON.parse(lastScore.answerResult);
            for (var i = 0; i < arr.length; i++) {
                for (var j = 0; j < arr[i].list.length; j++) {
                    for (var q = 0; q < idResultArr.length; q++) {
                        if(arr[i].list[j].id == idResultArr[q]){
                            arr[i].list[j].flag = true;
                            break;
                        }else{
                            arr[i].list[j].flag = false;
                        }
                    }
                }
            }
        }
        return arr;
    }
    /**
     * 将获取的评估题目进行数据处理(Alberta婴幼儿运动量)
     */
    servers.aimsData = function(data,lastScore){
        var arr = [];
        for( var key in data){
            var obj = {
                "label":key,
                'list':data[key]
            };
            arr.push(obj);
        }
        var type = ["prone-","dorsa-","seats-","stand-"];
        for (var i = 0; i < arr.length; i++) {
            arr[i].type = type[i];
            for (var j = 0; j < arr[i].list.length; j++) {
                arr[i].list[j].flag = false;
            }
        }
        if(lastScore != null){
            var idResultObj = JSON.parse(lastScore.answerResult);
            var resultObj = JSON.parse(lastScore.result);
            var idResultArr = [];
            for(var key in idResultObj){
                var obj = {
                    "label":key,
                    "idArr":idResultObj[key],
                };
                if(key == "prone"){
                    obj = $.extend(obj,{"num":resultObj[key].windowProne});
                }else if(key == "dorsa"){
                    obj = $.extend(obj,{"num":resultObj[key].windowDorsa});
                }else if(key == "seats"){
                    obj = $.extend(obj,{"num":resultObj[key].windowSeats});
                }else if(key == "stand"){
                    obj = $.extend(obj,{"num":resultObj[key].windowStand});
                }
                idResultArr.push(obj);
            }
            for (var i = 0; i < arr.length; i++) {
                for (var j = 0; j < arr[i].list.length; j++) {
                    for (var p = 0; p < idResultArr[i].idArr.length; p++) {
                        if( arr[i].list[j].id == idResultArr[i].idArr[p] ){
                            arr[i].list[j].flag = true;
                            break;
                        }else{
                            arr[i].list[j].flag = false;
                        }
                        arr[i].num = idResultArr[i].num;
                        if(arr[i].num > 0){
                            arr[i].flag = true;
                        }else{
                            arr[i].flag = false;
                        }
                    }
                }
            }
        }
        return arr;
    }
    /**
     * 获取答案（map）构造方法
     */
    var hashmap = function(){
        var HashMap = function(){
            this.map = {};
        }
        HashMap.prototype = {
            constructor : HashMap,
            put : function(key,value){
                this.map[key] = value;
            },
            get : function(key){
                if(this.map.hasOwnProperty(key)){
                    return this.map[key];
                }
                return null;
            },
            remove : function(key){
                if(this.map.hasOwnProperty(key)){
                    return delete this.map[key];
                }
                return false;
            },
            removeAll : function(){
                this.map = {};
            },
            keySet : function(){
                var _keys = [];
                for(var i in this.map){
                    _keys.push(i);
                }
                return _keys;
            }
        };
        return HashMap;
    };
    /**
     * 获取评估问卷答案(高危儿孕产妇)
     */
    servers.getAssesshighriskResultData = function(dom){
        var HashMap = hashmap();
        var hashMapQues = new HashMap();
        dom.find("input:checked").each(function(){
            var score = $(this).attr("score");
            var val = $(this).val();
            var id = $(this).attr("id");
            hashMapQues.put(id ,{
                "score":score,
                "questions":val,
            });
        });
        return hashMapQues;
    }
    /**
     * 获取评估问卷答案(Alberta婴幼儿运动量)
     */
    servers.getAssessAIMSResultData = function(dom){
        var data = {
            "prone":[],
            "dorsa":[],
            "seats":[],
            "stand":[]
        };
        var HashMap = hashmap();
        dom.find(".asCard-aims-list").each(function(i){
            var This = this;
            var hashMapQues = new HashMap();
            var curkey;
            $(This).find(".asCard-aims.active").each(function(j){
                var score = $(this).attr("score");
                var id = $(this).attr("id").split("-")[1];
                curkey = $(this).attr("id").split("-")[0];
                hashMapQues.put(id ,{
                    "score":score,
                });
            });
            var idArr = hashMapQues.keySet();
            for(var key in data){
                if(key == curkey){
                    data[key] = idArr;
                }
            }
        });
        return JSON.stringify(data);
    }
    /**
     * 处理获取的评估问卷答案(高危儿孕产妇)
     */
    servers.handleAssessResult = function(params,hashMapQues){
        var result = [];
        var scoresTotal = 0;
        for(var key in hashMapQues.map){
            scoresTotal += hashMapQues.get(key).score*1;
            result.push({
                "id":key,
                "ques":hashMapQues.get(key).questions
            });
        }
        var idArr = hashMapQues.keySet();
        var level = scoresTotal <= 5 ? "轻度高危" : scoresTotal >= 20 ? "重度高危":"中度高危";
        var HashMap = hashmap();
        var finRes = new HashMap();
        finRes.put("lens",result.length);//项数；
        finRes.put("scoresTotal",scoresTotal);//总分数；
        finRes.put("level",level);//程度；
        finRes.put("result",result);//题目；
        idArr = idArr instanceof Object ? JSON.stringify(idArr) : idArr;
        finRes = finRes instanceof Object ? JSON.stringify(finRes) : finRes;
        params = $.extend(params,{"postionIds":idArr,"postionScores":finRes});
        return params;
    }
    /**
     * 保存评估答案和评估结果
     */
    servers.saveAssessResult = function(params,callback){
        $bb.ajax({
            url: URL + "followup/service/patient/evaluation/getScore",
            data: JSON.stringify({
                data: {
                    "examinationPaperName":params.examinationPaperName,
                    "postionIds":params.postionIds,
                    "postionScores":params.postionScores,
                    "taskId":params.taskId,
                    "userId":params.userId,
                }
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,params);
                }else{
                    $bb.toastShow("保存失败！",1500);
                }
            }
        });
    };
    /**
     * 上传图片
     */
    servers.uploadMultiFile = function(obj,fd,callback){
        $bb.ajax({
            url: URL + "followup/service/treat/uploadMultiFile",
            processData: false,  // 告诉jQuery不要去处理发送的数据
            contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
            data: fd,
            success: function(data){
                if(data.success){
                    callback(obj,data.data);
                }else{
                    $bb.toastShow(data.msg ? data.msg :"上传图片失败！");
                }
            }
        });
    };

    /**
     * 判断问卷答案是否全为空
     */
    servers.isAllEmptyQuestValue = function(data){
        var flagA = true;  // 全为空
        for(var key in data){
            var flagB = true;
            if(data[key] != ""){
                if(data[key].indexOf("[") > -1 && data[key].indexOf("]") > -1){
                    var arr = JSON.parse(data[key]);
                    for (var i = 0; i < arr.length; i++) {
                        var flagC = true;
                        if( arr[i] == "" ){
                            flagC = flagC && true;
                        }else{
                            flagC = flagC && false;
                        }
                        flagB = flagB && flagC;
                        if(flagB == false) break;
                    }
                }else{
                    flagB = false;
                }
            }else{
                flagB = true;
            }   
            flagA = flagA && flagB;
            if(flagA == false) break;
        }
        return flagA;
    }

    /**
     * (融合基因题型)
     */
    // 查询项目
    servers.ajaxQueryProjectItem = function(configParams,obj,callback,params){
        $bb.ajax({
            url: URL + configParams.queryUrl,
            data:JSON.stringify({
                data : {
                    "configCode":configParams.configCode,
                    "configType":configParams.configType
                }
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,configParams,obj,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询项目失败！");
                }
            }
        });
    }
    // 添加项目
    servers.ajaxAddProjectItem = function(dataParams,params,callback){
        $bb.ajax({
            url: URL + dataParams.configParams.addUrl,
            data:JSON.stringify({
                data : params
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,dataParams);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "添加项目失败！");
                }
            }
        });
    }
    // 更新项目
    servers.ajaxUpdateProjectItem = function(dataParams,params,callback){
        $bb.ajax({
            url: URL + dataParams.configParams.updateUrl,
            data:JSON.stringify({
                data : params
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,dataParams);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "更新项目失败！");
                }
            }
        });
    }
    // 删除项目
    servers.ajaxDelProjectItem = function(dataParams,params,callback){
        $bb.ajax({
            url: URL + dataParams.configParams.delUrl,
            data:JSON.stringify({
                data : params
            }),
            success: function(data){
                if(data.success){
                    callback(data.data,dataParams);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "删除项目失败！");
                }
            }
        });
    }

    /**
     * 请求生长百分位(生长发育题型)
     */
    servers.ajaxGrowthPercentiles = function(params,callback,dom){
        $bb.ajax({
            url: URL + "followup/service/patient/growth/getGrowthPercentiles",
            data:JSON.stringify({
                data: params,
            }),
            success: function(data){
                if(data.success){
                    callback(dom,data.data.percentiles);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "计算百分位出错");
                }
            }
        });
    }

    /**
     * 请求最近一次生长发育记录(生长发育题型)
     */
    servers.ajaxLastGrowth = function(params,callback,dom,name,value,testTime,unit){
        $bb.ajax({
            url: URL + "followup/service/patient/patientTaskContentDataQuery",
            data:JSON.stringify({
                data: params,
            }),
            success: function(data){
                if(data.success){
                    if(data.data.values && data.data.task.finishDate){
                        callback(dom,name,data.data.task.finishDate,value,testTime,unit,data.data.values);
                    }
                }else{
                    $bb.toastShow(data.msg ? data.msg : "计算生长发育日均增长出错");
                }
            }
        });
    }

    /**
     * 请求生长曲线图(生长发育题型)
     */
    servers.ajaxGrowthCure = function(params,callback,className,label,gender){
        $bb.ajax({
            url: URL + "followup/service/patient/growth/getGrowthCurvedataByValue",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,className,label,gender);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "曲线图出错");
                }
            }
        });
    }

	return servers;
});